/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Interfaces;

import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import lemar.ConexionHibernate;
import lemar.entidad.AreaProducto;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.Query;
/**
 *
 * @author Lkokain
 */
public class ConsultarArea extends javax.swing.JPanel {

   private static SessionFactory sessionFactory = null;
    public ConsultarArea() {
        initComponents();
        cargarComboBox();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        cmbNombreArea = new javax.swing.JComboBox();
        jSeparator1 = new javax.swing.JSeparator();
        btnConsultarArea = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        txtIdArea = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        txtNombreArea = new javax.swing.JTextField();
        txtProductosArea = new javax.swing.JTextField();

        setBackground(new java.awt.Color(255, 255, 255));
        setMaximumSize(new java.awt.Dimension(747, 435));
        setMinimumSize(new java.awt.Dimension(747, 435));
        setPreferredSize(new java.awt.Dimension(747, 435));

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Consultar Area de Producto");

        jLabel2.setText("Nombre del area");

        cmbNombreArea.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cmbNombreArea.setToolTipText("Seleccione el nombre del área que desea consultar");

        btnConsultarArea.setText("Consultar");
        btnConsultarArea.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConsultarAreaActionPerformed(evt);
            }
        });

        jButton2.setText("Cancelar");
        jButton2.setToolTipText("Anula la operacion");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel4.setText("Identificacion");

        txtIdArea.setEditable(false);
        txtIdArea.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtIdAreaActionPerformed(evt);
            }
        });

        jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel5.setText("Producto");

        jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel6.setText("Nombre");

        txtNombreArea.setEditable(false);

        txtProductosArea.setEditable(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnConsultarArea, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(224, 224, 224)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cmbNombreArea, 0, 210, Short.MAX_VALUE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 299, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(txtIdArea))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(txtProductosArea))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(txtNombreArea)))
                .addGap(0, 224, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(60, 60, 60)
                .addComponent(jLabel1)
                .addGap(59, 59, 59)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cmbNombreArea, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(31, 31, 31)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(12, 12, 12)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(txtNombreArea, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtIdArea, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtProductosArea, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 91, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnConsultarArea)
                    .addComponent(jButton2))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton2ActionPerformed

    private void txtIdAreaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtIdAreaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtIdAreaActionPerformed

    private void btnConsultarAreaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConsultarAreaActionPerformed
        String nombre = "";
        
        List<AreaProducto> area = null;
        
        //Se extrae el nombre del proveedor seleccionado
        nombre = cmbNombreArea.getSelectedItem().toString();
        
        if(nombre.equalsIgnoreCase("<--Seleccione un Area de productos-->")){
            JOptionPane.showMessageDialog(null,"Seleccione un nombre de Area de Productos","Selección de datos",JOptionPane.ERROR_MESSAGE);
        }
        else{
            
            //Chunche de Hibernate (Inicio de sesion de hibernate)
            Session session = null;
            //Cadena de seleccion de HQL
            String hql = "FROM lemar.entidad.ConsultarArea AS p WHERE p.nombre = :nombre";
            try{
                try{
                    //Conexion a la BD
                    sessionFactory = ConexionHibernate.getSessionFactory();
                    //Apertura de la sesion
                    session = sessionFactory.openSession();
                    Transaction txt = session.beginTransaction();                                       
                    
                    //Extraccion de los datos del proveedor de la BD                    
                    Query query = session.createQuery(hql).setString("nombre", nombre);
                    
                    //Se extrae los registros del proveedor
                    area = query.list();
                    
                    //Se ponen los datos del proveedir en los campos de texto
                    //para su respectiva consulta
                    
                    txtNombreArea.setText(area.get(0).getNombre());
                    //txtCodigoArea.setText(area.get(0).getIdAreaProducto());
                    txtProductosArea.setText(area.get(0).getProducto());
                    txtIdArea.setText(area.get(0).getIdentificacion());
                    txt.commit();
                    
                     
                    }catch(Exception e){
                    System.out.println(e.getMessage());
                }
            } finally {
                //Finalizacion de la sesion de hibernate
                session.close();
                }
        }
    
    }//GEN-LAST:event_btnConsultarAreaActionPerformed

    private void cargarComboBox(){
        
        //Obtencion de todos los proveedores de la base de datos
        //para llenar el comboBox de manera dinamica
        
        //Variable que contendra la lista de proveedores
        List<AreaProducto> listaArea = null;
        
        //Inicializacion de session de hibernate
        Session session = null;
        try{
            try{
                //Chunces que ocupa Hibernate
                sessionFactory = ConexionHibernate.getSessionFactory();
                session = sessionFactory.openSession();
                Transaction tx = session.beginTransaction();
                
                //Obteniendo de la BD todos los proveedores                
                listaArea = session.createQuery("from AreaProducto").list();
                
                //Creando un modelo de comboBox                
                DefaultComboBoxModel modeloCombo = new DefaultComboBoxModel();
                
                //Poniendole un mensaje de seleccion (Pirmer elemento)
                 modeloCombo.addElement("<--Seleccione una area de producto-->");
                
                //Llenando el modelo de comboBox con los nombres de los proveedores
                for(AreaProducto p : listaArea) 
                { 
                    modeloCombo.addElement(p.getNombre());                     
                }
                
                //Agregando el modelo del comboBox al comboBox del panel
                cmbNombreArea.setModel(modeloCombo);
                
            }catch(Exception e){
                    System.out.println(e.getMessage());
                }
            }finally {
                session.close();
        }
        
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConsultarArea;
    private javax.swing.JComboBox cmbNombreArea;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField txtIdArea;
    private javax.swing.JTextField txtNombreArea;
    private javax.swing.JTextField txtProductosArea;
    // End of variables declaration//GEN-END:variables
}
